package com.hgyc.mom.tool.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.hgyc.mom.common.constant.Constants;
import com.hgyc.mom.common.exception.job.TaskException;
import com.hgyc.mom.common.util.StringUtils;
import com.hgyc.mom.common.util.poi.ExcelUtil;
import com.hgyc.mom.common.vo.Result;
import com.hgyc.mom.core.mybatis.QueryWrapperUtil;
import com.hgyc.mom.tool.entity.Job;
import com.hgyc.mom.tool.service.JobService;
import com.hgyc.mom.tool.util.CronUtils;
import com.hgyc.mom.tool.util.ScheduleUtils;
import com.hgyc.mom.tool.vo.JobParam;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.servlet.http.HttpServletResponse;
import org.quartz.SchedulerException;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.Arrays;
import java.util.List;

/**
 * 定时任务调度Controller
 *
 * @author fwj
 * @since 2025-05-08
 */
@Tag(name = "定时任务调度控制器", description = "定时任务调度控制器")
@RestController
@RequestMapping("/tool/job")
public class JobController {
    @Autowired
    private JobService jobService;

    @Operation(summary = "查询定时任务调度列表", description = "查询定时任务调度列表")
    @PostMapping("/pageList")
    public Result<IPage<Job>> pageList(@Parameter(description = "查询参数") @RequestBody JobParam jobParam) {
        Page<Job> page = new Page<>(jobParam.getPage(), jobParam.getPageSize());
        Job job = new Job();
        BeanUtils.copyProperties(jobParam, job);
        QueryWrapper<Job> wrapper = QueryWrapperUtil.build(job);
        IPage<Job> list = jobService.page(page, wrapper);
        return Result.success(list);
    }

    @Operation(summary = "导出定时任务调度列表", description = "导出定时任务调度列表")
    @PostMapping("/export")
    public void export(HttpServletResponse response, JobParam jobParam) {
        Job job = new Job();
        BeanUtils.copyProperties(jobParam, job);
        QueryWrapper<Job> wrapper = QueryWrapperUtil.build(job);
        List<Job> list = jobService.list(wrapper);
        ExcelUtil<Job> util = new ExcelUtil<>(Job.class);
        util.exportExcel(response, list, "定时任务调度数据");
    }

    @Operation(summary = "获取定时任务调度详细信息", description = "获取定时任务调度详细信息")
    @GetMapping(value = "/{id}")
    public Result getInfo(@Parameter(description = "定时任务调度ID") @PathVariable("id") Long id) {
        return Result.success(jobService.getById(id));
    }

    @Operation(summary = "新增定时任务调度", description = "新增定时任务调度")
    @PostMapping
    public Result save(@Parameter(description = "定时任务调度") @RequestBody Job job) {
        if (!CronUtils.isValid(job.getCronExpression()))
        {
            return Result.error("新增任务'" + job.getJobName() + "'失败，Cron表达式不正确");
        }
        else if (StringUtils.containsIgnoreCase(job.getInvokeTarget(), Constants.LOOKUP_RMI))
        {
            return Result.error("新增任务'" + job.getJobName() + "'失败，目标字符串不允许'rmi'调用");
        }
        else if (StringUtils.containsAnyIgnoreCase(job.getInvokeTarget(), new String[] { Constants.LOOKUP_LDAP, Constants.LOOKUP_LDAPS }))
        {
            return Result.error("新增任务'" + job.getJobName() + "'失败，目标字符串不允许'ldap(s)'调用");
        }
        else if (StringUtils.containsAnyIgnoreCase(job.getInvokeTarget(), new String[] { Constants.HTTP, Constants.HTTPS }))
        {
            return Result.error("新增任务'" + job.getJobName() + "'失败，目标字符串不允许'http(s)'调用");
        }
        else if (StringUtils.containsAnyIgnoreCase(job.getInvokeTarget(), Constants.JOB_ERROR_STR))
        {
            return Result.error("新增任务'" + job.getJobName() + "'失败，目标字符串存在违规");
        }
        else if (!ScheduleUtils.whiteList(job.getInvokeTarget()))
        {
            return Result.error("新增任务'" + job.getJobName() + "'失败，目标字符串不在白名单内");
        }
        return Result.success(jobService.save(job));
    }

    @Operation(summary = "修改定时任务调度", description = "修改定时任务调度")
    @PutMapping
    public Result update(@Parameter(description = "定时任务调度") @RequestBody Job job) {
        if (!CronUtils.isValid(job.getCronExpression()))
        {
            return Result.error("修改任务'" + job.getJobName() + "'失败，Cron表达式不正确");
        }
        else if (StringUtils.containsIgnoreCase(job.getInvokeTarget(), Constants.LOOKUP_RMI))
        {
            return Result.error("修改任务'" + job.getJobName() + "'失败，目标字符串不允许'rmi'调用");
        }
        else if (StringUtils.containsAnyIgnoreCase(job.getInvokeTarget(), new String[] { Constants.LOOKUP_LDAP, Constants.LOOKUP_LDAPS }))
        {
            return Result.error("修改任务'" + job.getJobName() + "'失败，目标字符串不允许'ldap(s)'调用");
        }
        else if (StringUtils.containsAnyIgnoreCase(job.getInvokeTarget(), new String[] { Constants.HTTP, Constants.HTTPS }))
        {
            return Result.error("修改任务'" + job.getJobName() + "'失败，目标字符串不允许'http(s)'调用");
        }
        else if (StringUtils.containsAnyIgnoreCase(job.getInvokeTarget(), Constants.JOB_ERROR_STR))
        {
            return Result.error("修改任务'" + job.getJobName() + "'失败，目标字符串存在违规");
        }
        else if (!ScheduleUtils.whiteList(job.getInvokeTarget()))
        {
            return Result.error("修改任务'" + job.getJobName() + "'失败，目标字符串不在白名单内");
        }
        return Result.success(jobService.updateById(job));
    }

    @Operation(summary = "删除定时任务调度", description = "删除定时任务调度")
    @DeleteMapping
    public Result remove(@Parameter(description = "删除ID") @RequestParam("ids") Long[] ids) {
        return Result.success(jobService.removeByIds(Arrays.asList(ids)));
    }

    /**
     * 定时任务状态修改
     */
    @PostMapping("/status/change")
    public Result changeStatus(@RequestBody Job job) throws SchedulerException
    {
        Job newJob = jobService.getById(job.getId());
        newJob.setStatus(job.getStatus());
        return Result.success(jobService.updateById(newJob));
    }

    /**
     * 定时任务立即执行一次
     */
    @PostMapping("/run")
    public Result run(@RequestBody Job job) throws TaskException {
        try {
            jobService.run(job);
        } catch (SchedulerException e) {
            throw new TaskException(e.getMessage(), TaskException.Code.TASK_ERROR);
        }
        return Result.success();
    }
}